using System;
using DG.Tweening;
using LitJson;
using UnityEngine;
namespace CGF
{
    public partial class PanelLeaseRenew : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private JsonData data;
        private Action<string> onSuccess;
        private int currDeviceType;
        private float priceVIP;

        public static void Open(JsonData data, JsonData shopData, int remainDays, Action<string> onSuccess)
        {
            var instance = UIManagerComponent.instance.OpenUI<PanelLeaseRenew>(UILayer.Normal, RootComponent.instance, true);
            instance.data = data;
            instance.onSuccess = onSuccess;
            instance.SetProsBindCompletedAction(() =>
            {
                instance.SetInfo(data, shopData, remainDays);
            });
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelLeaseRenew>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelLeaseRenew", layer, isFloat);
            BindProperties(transform);

            BtnClose.SetClick(Close);

            Vector2 pos = Dialog.rectTransform.anchoredPosition;
            pos.y = -680;
            Dialog.rectTransform.anchoredPosition = pos;
            Dialog.rectTransform.DOAnchorPosY(20, 0.2f).OnComplete(() =>
            {
                Dialog.rectTransform.DOAnchorPosY(0, 0.1f);
            });

            BtnRenew.SetClick(async () =>
            {
                if (UserInfo.balance < priceVIP)
                {
                    CGF.Dialog.Confirm(I18N_balance_not_enough, () =>
                    {
                        PanelRecharge.Open();
                    }, null, I18N_goto_rechage);
                    return;
                }
                var res = await Network.Post($"/v1/order/bot/{data["id"]}/renew", null);
                if (res.success)
                {
                    //刷新余额
                    await UserInfo.RefreshWallet();
                    //刷新剩余时间
                    onSuccess?.Invoke(res.jsonData["data"]["bot"]["expired_at"].ToString());
                    //关闭
                    Close();
                    //弹出成功
                    CGF.Dialog.Alert(I18N_renew_success);
                }
            });

            ReqData();
            gameObject.AddEnableEvent(ReqData);
        }

        private void SetInfo(JsonData data, JsonData shopData, int remainDays)
        {
            int type = (int)shopData["type"];
            bool isPreparing = (DateTime.Now - DateTime.Parse(data["created_at"].ToString())).TotalMinutes < Config.PreparingMinutes;
            bool isRunning = DateTime.Parse(data["expired_at"].ToString()) > DateTime.Now;
            Device.GetComponent<Device>().SetInfo(type, (int)shopData["period"], isRunning);
            string status = isRunning ? (isPreparing ? CommAssets.instance.I18N_preparing : CommAssets.instance.I18N_running) : CommAssets.instance.I18N_expired;
            TextState.text = status;
            GreenLight.gameObject.SetActive(isRunning);
            GreenLight.GetComponent<FlashLight>().SetColor(isPreparing);
            TextTitle.text = Utils.GetI18N(shopData["name"].ToString());
            TextTitleSub.text = $"{CommAssets.instance.I18N_pre_income}: {Utils.GetI18N(shopData["subtitle"].ToString()).Replace("\n", "")}";
            TextRemain.text = I18N_remain_days.Replace("{num}", remainDays.ToString());
            float priceDefault = (int)shopData["price"];
            priceVIP = priceDefault * UserInfo.discount;
            PriceVIP.text = $"{CommAssets.instance.I18N_price_vip}: {I18N.Currency} {StringHelper.Format2Decimal(priceVIP * 0.01f)}";
            PriceDefault.text = $"{CommAssets.instance.I18N_price_default}: {I18N.Currency} {StringHelper.Format2Decimal(priceDefault * 0.01f)}";
        }

        private async void ReqData()
        {
            var res = await Network.Get("/v1/user/wallet");
            JsonData wallet = res.jsonData["data"]["wallet"];
            UserInfo.balance = (int)wallet["balance"];
            Balance.text = $"{CommAssets.instance.I18N_wallet_balance} {I18N.Currency} {StringHelper.Format2Decimal(UserInfo.balance * 0.01f)}";
            EventManager.Emit(new Event_UserInfoUpdate());
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
